<?php

namespace app\apishop\controller;

use Common\Oss;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\apishop\controller\Base;
use think\Session;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/15
 * Time: 14:34
 */
class Product extends Base
{
    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @description: 获取所有商品
     * @return json
     */
    public function getProducApi()
    {
        $data = Request::instance()->post();
        // 查询筛选
        $where                   = [];
        $where['P.is_shelves']   = ['<>', 4];
        $where['P.supplier']     = $data['supplier_id'];
        if (array_key_exists('search', $data) && !empty($data['search'])) {
            // 商品名称
            if (array_key_exists('name', $data['search']) && !empty($data['search']['name'])) $where['P.name'] = ['LIKE', '%' . trim($data['search']['name']) . '%'];
            // 商品分类
            if (array_key_exists('category', $data['search']) && !empty($data['search']['category'])) {
                if (array_key_exists('category_ids', $data['search']['category']) && !empty($data['search']['category']['category_ids'])) $where['P.category_id'] = ['IN', implode(',', $data['search']['category']['category_ids'])];
                if (array_key_exists('type_ids', $data['search']['category']) && !empty($data['search']['category']['type_ids'])) $where['P.type_id'] = ['IN', implode(',', $data['search']['category']['type_ids'])];
                if (array_key_exists('small_type_ids', $data['search']['category']) && !empty($data['search']['category']['small_type_ids'])) $where['P.small_type_id'] = ['IN', implode(',', $data['search']['category']['small_type_ids'])];
                if (array_key_exists('brand_ids', $data['search']['category']) && !empty($data['search']['category']['brand_ids'])) $where['P.brand_id'] = ['IN', implode(',', $data['search']['category']['brand_ids'])];
            }
            // 商品价格
            if (array_key_exists('price', $data['search']) && !empty($data['search']['price'])) {
                if (array_key_exists('down', $data['search']['price']) && !empty($data['search']['price']['down'])) $where['S.price'][] = ['EGT', $data['search']['price']['down']];
                if (array_key_exists('up', $data['search']['price']) && !empty($data['search']['price']['up'])) $where['S.price'][] = ['ELT', $data['search']['price']['up']];
            }
            // 商品库存
            if (array_key_exists('stock', $data['search']) && !empty($data['search']['stock'])) {
                if (array_key_exists('down', $data['search']['stock']) && !empty($data['search']['stock']['down'])) $where['P.stock'][] = ['EGT', $data['search']['stock']['down']];
                if (array_key_exists('up', $data['search']['stock']) && !empty($data['search']['stock']['up'])) $where['P.stock'][] = ['ELT', $data['search']['stock']['up']];
            }
            // 是否上架
            if (array_key_exists('is_shelves', $data['search']) && !empty($data['search']['is_shelves'])) $where['P.is_shelves'] = ['IN', $data['search']['is_shelves']];
        }
        // 商品列表
        $product['data'] = Db::name('product')
            ->alias('P')
            ->field('P.is_include_tax,P.image,P.id,P.name,P.stock,P.category_id,P.type_id,P.small_type_id,P.brand_id,S.price,P.is_shelves,P.sale_num,P.unit')
            ->join('product_specification S', 'P.id = S.product_id','left')
            ->where('S.is_default', 1)
            ->where($where)
			->order('P.create_time desc')
            ->limit(($data['pageNumber'] - 1) * $data['pageSize'], $data['pageSize'])
            ->select();
        foreach ($product['data'] as $k => $v) {
            $product['data'][$k]['price']       = sprintf("%.2f", $v['price']);
            $type                               = $this->getProductType([$v['category_id'], $v['type_id'], $v['small_type_id']]);
            $product['data'][$k]['category_id'] = $type['category'].'/'.$type['category_e'];
            if($v['brand_id'] == null || $v['brand_id'] == '' || $v['brand_id'] == 0 || $v['brand_id'] == '0'){
            $product['data'][$k]['brand_id'] = '';
            }else{
                $product['data'][$k]['brand_id']    = Db::name('base_data')->field('name,name_english')->where('type_menu', 2)->find($v['brand_id'])['name_english'];
            }
        }
        $product['pageNumber'] = $data['pageNumber'];
        if ($product['data'] === FALSE) return $result = json(Config::get('code.error'));
        // 商品总量
        $product['count'] = Db::name('product')
            ->alias('P')
            ->join('product_specification S', 'P.id = S.product_id','left')
            ->where('S.is_default', 1)
            ->where($where)
            ->count();
        return json($product);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-15
     * @rewriter:yangjian
     * @rewriter_date:2018-01-25
     * @description: 商品管理 添加查询条件 供应商ID
     * @return json
     */
    public function getProductList()
    {
        $data = Request::instance()->post();
        if (array_key_exists('types', $data) && !empty($data['types'])) {
            $product = Db::name('product')
                ->alias('P')
                ->join('product_specification S', 'S.product_id = P.id')
                ->field('P.id,P.status,P.image as image,P.name as name,S.unit as unit,S.price as price,S.specification as specification,S.packing_proportion as packing_proportion')
                ->where('P.is_shelves', $data['types'])
                ->where('P.supplier', $data['supplier_id'])
                ->group('P.id')
                ->select();
            //$aa      = Db::name('product')->getLastSql();
            if ($product !== FALSE) {
                if (!empty($product)) {
                    foreach ($product as $key => $value)
                    {
                        $product[$key]['price'] = sprintf("%.2f",$value['price']);
                    }
                    $result          = Config::get('code.success');
                    $result['data']  = $product;
                    $result['count'] = count($product);
                } else {
                    $result          = Config::get('code.null');
                    $result['data']  = '';
                    //$result['count'] = $aa;
                }
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-15
     * @rewriter:
     * @rewriter_date:
     * @description: 商品详细信息
     * @return json
     */
    public function getProductInfo()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            $id = $data['id'];
            $product = Db::name('product')
                ->alias('P')
                ->join('product_specification S', 'P.id = S.product_id')
                ->where('S.is_default',1)
                ->field('P.origin,P.category_id as category_id,P.type_id as type_id,P.small_type_id as small_type_id,P.brand_id as brand_id,P.image as image,P.name as name,S.specification as specification,S.price as price,P.stock as stock,P.sale_num as sale_num,GROUP_CONCAT(S.id) as ids,GROUP_CONCAT(S.packing_proportion) as packings,GROUP_CONCAT(S.price) as prices, P.unit')
                ->find($id);
            $product_specification = Db::table('product_specification')->where(['product_id'=>$id,'flag'=>1])->select();
            foreach ($product_specification as $k=>$v){
                $product_specification[$k]['price']  = number_format($v['price'],2,'.','');
            }
            $images = Db::name('product_image')
                    ->alias('I')
                    ->join('image M', 'I.image_id = M.id')
                    ->field('M.image_url as image')
                    ->where('I.product_id',$id)
                    ->select(); 
            if ($product !== FALSE) {
                if (!empty($product)) {
                    $res = $this->getProductType([$product['category_id'], $product['type_id'],$product['small_type_id']]);
                    $product['brand'] = Db::name('base_data')->field('name,name_english')->where('type_menu', 2)->find($product['brand_id'])['name'];
                    $product['brand_e'] = Db::name('base_data')->field('name,name_english')->where('type_menu', 2)->find($product['brand_id'])['name_english'];
                    foreach ($res as $k => $v) {
                        $product[$k] = $v;
                    }
                    $product['images'] = $images;
                    $product['product_specification'] = $product_specification;
                    $product['price']  = number_format($product['price'],2,'.','');
                    $result            = Config::get('code.success');
                    $result['data']    = $product;
                } else {
                    $result = Config::get('code.null');
                }
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description: 端新增商品
     * @return json
     */
    public function addProduct()
    {
        $data = Request::instance()->post();
        if (empty($data)) return json(Config::get('code.error'));
        $img     = $data['img'];
        $imgs    = $data['imgs'];
        $price   = (Float)$data['price'];
        $unit    = $data['unit'];
        if (empty($data['number']) || !array_key_exists('number',$data)){
            $number = 1;
        }else{
            $number  = $data['number'];
        }
        if (!empty($data['specification'])){
            $specification = $data['specification'];
        }
        if (empty($data['brand_id'])){ // 品类
            $data['brand_id'] == null;
        }else{
            $data['brand_id']  = is_array($data['brand_id']) ? $data['brand_id'][0] : $data['brand_id'];
        }
        if (empty($data['small_type_id'])){ // 品牌
            $data['small_type_id'] == null;
        }else{
            $data['small_type_id']  = is_array($data['small_type_id']) ? $data['small_type_id'][0] : $data['small_type_id'];
        }
        $data['category_id']    = is_array($data['category_id']) ? $data['category_id'][0] : $data['category_id'];
        $data['type_id']        = is_array($data['type_id']) ? $data['type_id'][0] : $data['type_id'];
        if (array_key_exists('supplier_id', $data)) $data['supplier'] = $data['supplier_id'];
        unset($data['supplier_id']);
        unset($data['type']);
        unset($data['img']);
        unset($data['imgs']);
        unset($data['price']);
        unset($data['token']);
        unset($data['number']);
        unset($data['specification']);
        Db::startTrans();
        try {
            if (array_key_exists('busSpecisStr', $data)) {
                $busSpecisStr = $data['busSpecisStr'];
                $busPricesStr = $data['busPricesStr'];
                $busNumberStr = $data['busNumberStr'];
                $busSpecisArr = explode(',', $busSpecisStr);
                $busPricesArr = explode(',', $busPricesStr);
                $busNumberArr = explode(',', $busNumberStr);
                unset($data['busSpecisStr']);
                unset($data['busPricesStr']);
                unset($data['busNumberStr']);
            } else {
                $busSpecisArr = [];
                $busPricesArr = [];
                $busNumberArr = [];
            }
            $data['create_time'] = date("Y-m-d H:i:s", time());
            $product_id =Db::name('product')->insertGetId($data);
            changeGoodsNum($product_id,1);
            if (!empty($busSpecisStr)) {
                foreach ($busSpecisArr as $k => $v) {
                    $save = [];
                    $save['product_id']         = $product_id;
                    $save['packing_proportion'] = $busNumberArr[$k];
                    $save['unit']               = $v;
                    $save['specification']      = $busNumberArr[$k].$v;
                    $save['price']              = $busPricesArr[$k];
                    $save['flag']               = 1;
                    $save['is_default']         = 0;
                    Db::name('product_specification')->insert($save);
                }
            }
            if (!empty($specification)) {
                foreach ($specification as $k => $v) {
                    $save = [];
                    $save['product_id']         = $product_id;
                    $save['packing_proportion'] = $v['number'];
                    $save['unit']               = $v['speci'];
                    $save['specification']      = $v['number'] . $v['speci'];
                    $save['price']              = $v['price'];
                    $save['flag']               = 1;
                    $save['is_default']         = 0;
                    Db::name('product_specification')->insert($save);
                }
            }
            $default_s['product_id']         = $product_id;
            $default_s['packing_proportion'] = $number;
            $default_s['unit']               = $unit;
            $default_s['specification']      = $number.$unit;
            $default_s['price']              = $price;
            $default_s['is_default']         = 1;
            $default_s['flag']               = 1;
            Db::name('product_specification')
                ->insert($default_s);
            if (!empty($img)) {
                if (!is_array($img)) $img = explode(',', $img);
                foreach ($img as $k => $v) {
                    $info['name']        = $data['name'];
                    $info['image_url']   = $v;
                    $info['create_time'] = date("Y-m-d H:i:s", time());
                    Db::name('image')
                        ->insert($info);
                    $image_id = Db::name('image')->getLastInsID();
                    Db::name('product_image')->insert(['product_id' => $product_id, 'type' => 1, 'image_id' => $image_id]);
                }
            }
            if (!empty($imgs)) {
                if (!is_array($imgs)) $imgs = explode(',', $imgs);
                foreach ($imgs as $k => $v) {
                    $info['name']        = $data['name'];
                    $info['image_url']   = $v;
                    $info['create_time'] = date("Y-m-d H:i:s", time());
                    Db::name('image')
                        ->insert($info);
                    $image_id = Db::name('image')->getLastInsID();
                    Db::name('product_image')->insert(['product_id' => $product_id, 'type' => 0, 'image_id' => $image_id]);
                }
            }
            Db::commit();
            return json(Config::get('code.success'));
        } catch (Exception $e) {
            Db::rollback();
            return json(Config::get('code.error'));
        }
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @description: 上架商品
     * @return json
     */
    public function upProduct()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            $res = Db::name('product')
                ->where('id', $data['id'])
                ->update(['is_shelves' => 1]);
            if ($res !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @description: 下架商品
     * @return json
     */
    public function downProduct()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            $res = Db::name('product')
                ->where('id', $data['id'])
                ->update(['is_shelves' => 2]);
            if ($res !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-04-09T21:24:12+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:修改Shelves
     * @param:
     */
    public function ChangeProductShelves()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            $shelves = $data['tag'];
            $res = Db::name('product')
                ->where('id', $data['id'])
                ->update(['is_shelves' => $shelves]);
            if ($res !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-04-09T21:24:35+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:修改商品库存，单价
     * @param:
     */
    public function ChangeProductInfo()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])||empty($data['tag'])) {
            $result = Config::get('code.mistake');
            return json($result);
        }
        $tag    = $data['tag'];
        $id     =  $data['id'];
        if($tag=='stock'){
            $save['stock'] = $data['stock'];
            $res = Db::name('product')
                ->where('id', $id)
                ->update($save);
            if ($res !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
            return json($result);
        }else if($tag=='price'){
            $save['price'] =$data['price'];
            $Re = Db::name('product_specification')
                ->where('product_id', $id)
                ->where('is_default', 1)
                ->update($save);
            if ($Re !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
            return json($result);
        }else if($tag=='unit'){         //修改单位
            $save['unit']               = $data['unit'];
            $save['specification']      = $data['number'].$data['unit'];
            $Re = Db::name('product_specification')
                ->where('product_id', $id)
                ->where('is_default', 1)
                ->update($save);
            $Res = Db::name('product')
                ->where('id', $id)
                ->update($save);
            if ($Re!== FALSE && $Res!== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
            return json($result);
        }else if($tag=='number'){       //修改数量
            $save['packing_proportion'] = $data['number'];
            $save['specification']      = $data['number'].$data['unit'];
            $Re = Db::name('product_specification')
                ->where('product_id', $id)
                ->where('is_default', 1)
                ->update($save);
            $Res = Db::name('product')
                ->where('id', $id)
                ->update($save);
            if ($Re!== FALSE && $Res!== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
            return json($result);
        }
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-04-09T21:25:09+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:删除规格
     * @param:
     */
    public function delProductSpeci(){
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            $result = Config::get('code.mistake');
            return json($result);
        }
        $id =  $data['id'];
        $update['flag'] = 0;
        $Re = Db::name('product_specification')
                ->where('id', $id)
                ->where('is_default', 0)
                ->update($update);
        if ($Re !== FALSE) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-04-09T21:25:27+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:添加规格
     * @param:
     */
    public function addProductSpeci(){
        $data = Request::instance()->post();
        if (empty($data['product_id'])||empty($data['price'])||empty($data['number'])||empty($data['unit'])) {
            $result = Config::get('code.mistake');
            return json($result);
        }
        $save['product_id']         =  $data['product_id'];
        $save['price']              =  $data['price'];
        $save['packing_proportion'] =  $data['number'];
        $save['specification']      =  $data['number'].$data['unit'];
        $save['flag']               =  1;
        $save['unit']               =  $data['unit'];
        $save['is_default']         =  0;
        $Re = Db::name('product_specification')->insert($save);
        if ($Re) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }
    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description: 删除商品
     * @return json
     */
    public function delProduct()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            if (is_array($data['id'])) {
                DB::startTrans();
                try {
                    foreach ($data['id'] as $v) {
                        Db::name('product')
                            ->where('id', $v)
                            ->update(['is_shelves' => 4]);
                        changeGoodsNum($v,0);
                    }
                    Db::commit();
                    $result = Config::get('code.success');
                } catch (Exception $e) {
                    $result = Config::get('code.error');
                    Db::rollback();
                }
            } else {
                $res = Db::name('product')
                    ->where('id', $data['id'])
                    ->update(['is_shelves' => 4]);
                changeGoodsNum($data['id'],0);
                if ($res === FALSE) return json($result = Config::get('code.error'));
                $result = Config::get('code.success');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-23
     * @rewriter:
     * @rewriter_date:
     * @param:
     * @description: 获取商品分类三级联动数据
     * @return json
     */
    public function getThreeType()
    {
        $data = Request::instance()->post();
        if (array_key_exists('parent_id', $data) && !empty($data['parent_id'])) {
            $parent_id = implode(',', $data['parent_id']);
            $info      = Db::name('base_data')
                ->field('id,name,level,name_english')
                ->where("parent_id in ($parent_id)")
                ->where(['type_menu' => 1, 'flag' => 1])
                ->select();
        } else {
            $info = Db::name('base_data')
                ->field('id,name,level,name_english')
                ->where(['type_menu' => 1, 'flag' => 1, 'parent_id' => 0])
                ->select();
        }
        if ($info === FALSE) return json(Config::get('code.error'));
        return json($info);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description: 获取所有品牌数据
     * @return json
     */
    public function getThreeBrand()
    {
        $data = Request::instance()->post();
        $where['flag'] = 1;
        $where['parent_id'] = array('in',$data['pid']);
        $info = Db::name('base_data')
            ->where($where)
            ->select();
        if ($info === FALSE) return json(Config::get('code.error'));
        return json($info);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @param $arr : 类别id、种类id、品牌id
     * @description: 获取商品类别、种类
     * @return json
     */
    public function getProductType($arr = array())
    {
        if (empty($arr)) {
            $type = Db::name('base_data')
                ->where('type_menu', 1)
                ->select();
            if ($type !== FALSE) {
                if (!empty($type)) {
                    $result         = Config::get('code.success');
                    $result['data'] = $type;
                } else {
                    $result = Config::get('code.null');
                }
            } else {
                $result = Config::get('code.error');
            }
        } else {
            if (is_array($arr)) {
                foreach ($arr as $v) {
                    $data[] = Db::name('base_data')
                                  ->field('name,name_english')
                                  ->where('type_menu', 1)
                                  ->find($v);
                }
                if ($data !== FALSE) {
                    if (!empty($data)) {
                        $result['category']   = !empty($data[0]['name']) ? $data[0]['name'] : NULL;
                        $result['type']       = !empty($data[1]['name']) ? $data[1]['name'] : NULL;
                        $result['small_type'] = !empty($data[2]['name']) ? $data[2]['name'] : NULL;
                        $result['category_e']   = !empty($data[0]['name_english']) ? $data[0]['name_english'] : NULL;
                        $result['type_e']       = !empty($data[1]['name_english']) ? $data[1]['name_english'] : NULL;
                        $result['small_type_e'] = !empty($data[2]['name_english']) ? $data[2]['name_english'] : NULL;
                        return $result;
                    }
                }
            }
            $result['category'] = $result['small_type'] = $result['type'] = NULL;
            return $result;
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @description: 获取所有商品类别、种类、品牌
     * @return json
     */
    public function getAllProductType()
    {
        $data = Request::instance()->post();
        if (!empty($data['type']) && $data['type'] == 'APP'){
            $res = Db::name('base_data')
                ->field('id,name,name_english,parent_id,level,leaf,type_menu')
                ->where('flag',1)
                ->select();
        }else{
            $res = Db::name('base_data')
                ->field('id,name,name_english,parent_id,level,leaf,type_menu')
                ->where('flag',1)
                ->select();
        }
        if ($res === FALSE) return json(Config::get('code.error'));
        $result = [];
        foreach ($res as $k => $v) {
            if ($v['level'] == 0 && $v['type_menu'] == 1) {
                $result['category'][] = $v;
            } else if ($v['level'] == 1) {
                $result['type'][] = $v;
            } else if ($v['level'] == 2) {
                $result['small_type'][] = $v;
            }
            if ($v['type_menu'] == 2) {
                $result['brand'][] = $v;
            }
        }
        foreach ($result['small_type'] as $kk=>$vv){
            foreach ($result['brand'] as $key=>$value){
                if ($value['parent_id'] == $vv['id']){
                    $result['small_type'][$kk]['brand'][] = $value;
                }
            }
        }
        $result['status'] = 200;
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-26
     * @rewriter:
     * @rewriter_date:
     * @description: 上传图片
     * @return json
     */
    public function uploadImg()
    {
        $data = input();//Request::instance()->post();
        if (!array_key_exists('dir', $data) || empty($data['dir'])) return json(Config::get('code.mistake'));
        if (!empty($_FILES['img'])){
            if (is_array($_FILES['img']['tmp_name'])){
                foreach ($_FILES['img']['tmp_name'] as $v){
                    $size = getimagesize($v);
                    if ($size[0] != $size[1]){
                        $res['status'] = 209;
                        $res['msg'] = '请上传正确大小的图片';
                        return json($res);
                    }
                }
            }else{
                $size = getimagesize($_FILES['image']['tmp_name']);
                if ($size[0] != $size[1]){
                    $res['status'] = 209;
                    $res['msg'] = '请上传正确大小的图片';
                    return json($res);
                }
            }
        }
        $ossClient = new Oss();
        $files     = $ossClient->uploadFile($data['dir'], $data['name']);
        if ($files === FALSE) return json(Config::get('code.error'));
        $result                = Config::get('code.success');
        $result[$data['name']] = $files;
        return json($result);
    }
    public function uploadImg1()
    {
        $data = input();//Request::instance()->post();
        if (!array_key_exists('dir', $data) || empty($data['dir'])) return json(Config::get('code.mistake'));
        if (!empty($_FILES['img1'])){
            if (is_array($_FILES['img1']['tmp_name'])){
                foreach ($_FILES['img1']['tmp_name'] as $v){
                    $size = getimagesize($v);
                    if ($size[0] != $size[1]){
                        $res['status'] = 209;
                        $res['msg'] = '请上传正确大小的图片';
                        return json($res);
                    }
                }
            }else{
                $size = getimagesize($_FILES['image']['tmp_name']);
                if ($size[0] != $size[1]){
                    $res['status'] = 209;
                    $res['msg'] = '请上传正确大小的图片';
                    return json($res);
                }
            }
        }
        $ossClient = new Oss();
        $files     = $ossClient->uploadFile($data['dir'], $data['name']);
        if ($files === FALSE) return json(Config::get('code.error'));
        $result                = Config::get('code.success');
        $result[$data['name']] = $files;
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-02-04T16:48:59+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:
     * @param:
     * @return [type] [description]
     */
    public function uploadImgtest(){
        $post  = request()->post();
        if (!array_key_exists('dir', $post) || empty($post['dir']) || !array_key_exists('name', $post) || empty($post['name'])) return json(Config::get('code.mistake'));
        $ossClient = new Oss();
        $files     = $ossClient->uploadFile($post['dir'], 'file');
        if ($files === FALSE) return json(Config::get('code.mistake'));
        $result          = Config::get('code.success');
        $result['files'] = $files;
        return json($result);
    }
    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-29
     * @rewriter:
     * @rewriter_date:
     * @description: 删除图片
     * @return json
     */
    public function delImg()
    {
        $post = Request::instance()->post();
        if (!array_key_exists('path', $post) || empty($post['path'])) return json(Config::get('code.mistake'));
        $ossClient = new Oss();
        $res       = $ossClient->deleteFile($post['path']);
        if ($res === FALSE) return json(Config::get('code.mistake'));
        return json(Config::get('code.success'));
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-18
     * @rewriter:
     * @rewriter_date:
     * @description: 优惠管理
     * @return json
     */
    public function getDiscountList()
    {
        $data  = Request::instance()->post();
        $where ['d.status'] = ['>',0];
        $where ['d.supplier_id'] = $data['supplier_id'];
        if (array_key_exists('search', $data) && !empty($data['search'])) {
            if (array_key_exists('product_name', $data['search']) && !empty($data['search']['product_name'])){
//                $where  = [
//                    'p.name'                    => ['like','%'.trim($data['search']['product_name']).'%'],
//                ];
                $where['p.name'] = ['like','%'.trim($data['search']['product_name']).'%'];
            }
            if (array_key_exists('discount_type', $data['search']) && !empty($data['search']['discount_type'])){
//                $where  = [
//                    'd.type'                    => $data['search']['discount_type'],
//                ];
                $where['d.type'] = $data['search']['discount_type'];
            }
            if (array_key_exists('discount_status', $data['search']) && !empty($data['search']['discount_status'])){
//                $where  = [
//                    'd.status'                  => $data['search']['discount_status'],
//                ];
                $where['d.status'] = $data['search']['discount_status'];
            }
        }
        $info = Db::name('discount')
            ->field('id,start_time,end_time,status')
            ->where('supplier_id',$data['supplier_id'])
            ->where('status','<>',0)
            ->select();
        foreach ($info as $k=>$v){
            $time = date("Y-m-d H:i:s", time());
            if ($v['end_time']<$time){
                Db::table('discount')->where(['id'=>$v['id']])->setField('status',0);
            }
        }
        $where['supplier_id'] = $data['supplier_id'];

        $discount['data'] = Db::name('discount')
            ->alias('d')
            ->field('d.id, d.name, d.type, d.start_time, d.end_time, d.add_time, d.status, p.name as product_name')
            ->join('product p','p.id = d.product_id','left')
            ->where($where)
            ->limit(($data['pageNumber'] - 1) * $data['pageSize'], $data['pageSize'])
            ->order('d.add_time desc')
            ->select();
        foreach ($discount['data'] as $k =>   $v) {
            if (array_key_exists('type', $v) && !empty($v['type'])) {
                if ($v['type'] == 1) {
                    $discount['data'][$k]['type'] = '满减';
                } elseif ($v['type'] == 2) {
                    $discount['data'][$k]['type'] = '满送';
                }
            }
        }
        $discount['pageNumber'] = $data['pageNumber'];
        if ($discount['data'] === FALSE) return $result = json(Config::get('code.error'));
        $discount['count'] = Db::name('discount')->alias('d')->join('product p','p.id = d.product_id')->where($where)->count();
        return json($discount);
    }

    public function getDiscount()
    {
        $post  = Request::instance()->post();
        if (!empty($post['supplier_id']) && !empty($post['page_no']) && !empty($post['page_size'])){
            $pageNo     = $post['page_no'];
            $pageSize   = $post['page_size'];
            $info = Db::name('discount')
                ->field('id,start_time,end_time,status')
                ->where('supplier_id',$post['supplier_id'])
                ->where('status','<>',0)
                ->select();
            foreach ($info as $k=>$v){
                $time = date("Y-m-d H:i:s", time());
                if ($v['end_time']<$time){
                    Db::table('discount')->where(['id'=>$v['id']])->setField('status',0);
                }
            }
            $discount['data'] = Db::name('discount')
                ->alias('d')
                ->field('d.*, p.name as product_name, p.image as product_image, ps.price')
                ->join('product p','p.id = d.product_id')
                ->join('product_specification ps','ps.product_id = d.product_id')
                ->where('d.status','<>',0)
                ->where('d.supplier_id',$post['supplier_id'])
                ->where('ps.is_default',1)
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->order('d.add_time desc')
                ->select();
            foreach ($discount['data'] as $k => $v) {
                $discount['data'][$k]['price']         = number_format($v['price'], 2, '.', '');
                if (array_key_exists('type', $v) && !empty($v['type'])) {
                    if ($v['type'] == 1) {
                        $discount['data'][$k]['type'] = '满减';
                    } elseif ($v['type'] == 2) {
                        $discount['data'][$k]['type'] = '满送';
                    }
                }
            }
            if ($discount['data'] === FALSE) return $result = json(Config::get('code.error'));
            $discount['count']  = Db::name('discount')->alias('d')->join('product p','p.id = d.product_id')->where('d.status','<>',0)->count();
            $result = Config::get('code.success');
            $result['discount'] = $discount;
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-02-03T16:48:59+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:新增优惠
     * @param:
     */
    public function addDiscount()
    {
        $post  =  Request::instance()->post();
        if (!array_key_exists('type', $post) || empty($post['type'])){
            return json(Config::get('code.mistake'));
        }
        $post['condition_money'] = $post['product_price'] * $post['condition_num'];
        $data = [];
        $data['name']                   = $post['name'];
        $data['type']                   = $post['type'];
        $data['condition_money']        = $post['condition_money'];
        $data['condition_num']          = $post['condition_num'];
        $data['relief_money']           = $post['relief_money'];
        $data['start_time']             = $post['start_time'];
        $data['end_time']               = $post['end_time'];
        $data['add_time']               = date("Y-m-d H:i:s",time());
        $data['supplier_id']            = $post['supplier_id'];
        $data['product_id']             = $post['id'];
        $data['give_product']           = $post['give'];
        $data['status']                 = 1;
        $discount  = Db::name('discount')
            ->where(['supplier_id'=>$data['supplier_id'],'product_id'=>$data['product_id'],'status'=>1])
            ->find();
        if ($discount){
            $result = Config::get('code.error');
            $result['msg'] = '该商品已参与其他活动';
            return json($result);
        }else{
            $Re = Db::name('discount')->insert($data);
            if($Re !== false){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.null');
            }
            return json($result);
        }
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-02-08
     * @rewriter:
     * @rewriter_date:
     * @description: 删除活动
     * @return json
     */
    public function delDiscount()
    {
        $post = Request::instance()->post();
        if (array_key_exists('id', $post) && !empty($post['id'])) {
            $time       = date("Y-m-d H:i:s", time());
            if (is_array($post['id'])) {
                DB::startTrans();
                try {
                    foreach ($post['id'] as $v) {
                        $discount   = Db::name('discount')->where('id', $v)->find();
                        $start_time = $discount['start_time'];
                        if ($start_time < $time){
                            $result = Config::get('code.error');
                            $result['msg'] = '当前优惠活动已生效,不能删除';
                            return json($result);
                        }else{
                            Db::name('discount')
                                ->where('id', $v)
                                ->update(['status' => 0]);
                        }
                    }
                    Db::commit();
                    $result = Config::get('code.success');
                } catch (Exception $e) {
                    $result = Config::get('code.error');
                    Db::rollback();
                }

            } else {
                $discount   = Db::name('discount')->where('id', $post['id'])->find();
                $start_time = $discount['start_time'];
                if ($start_time < $time){
                    $result = Config::get('code.error');
                    $result['msg'] = '当前优惠活动已生效,不能删除';
                    return json($result);
                }else{
                    $res = Db::name('discount')
                        ->where('id', $post['id'])
                        ->update(['status' => 0]);
                    if ($res === FALSE) return json($result = Config::get('code.error'));
                    $result = Config::get('code.success');
                }
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-03-01
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 上架优惠
     * @return array|Json
     */
    public function upDiscount(){
        $post = Request::instance()->post();
        if (!empty($post['id'])) {
            $discount   = Db::name('discount')->where('id', $post['id'])->find();
            $count      = Db::name('discount')->where(['product_id'=>$discount['product_id'],'status'=>1])->count();
            if ($count>0){
                $result = Config::get('code.error');
                $result['msg'] = '该商品已参加其他开启状态活动';
                return json($result);
            }
            $end_time   = $discount['end_time'];
            $time       = date("Y-m-d H:i:s", time());
            if ($time > $end_time){
                $result = Config::get('code.error');
                $result['msg'] = '当前优惠活动已过期';
                return json($result);
            }
            $res = Db::name('discount')
                ->where('id', $post['id'])
                ->update(['status' => 1]);
            if ($res !== FALSE) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-03-01
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 下架优惠
     * @return array|Json
     */
    public function downDiscount(){
        $post = Request::instance()->post();
        if (array_key_exists('id', $post) && !empty($post['id'])) {
            $discount   = Db::name('discount')->where('id', $post['id'])->find();
            $start_time = $discount['start_time'];
            $time       = date("Y-m-d H:i:s", time());
            if ($start_time < $time){
                $result = Config::get('code.error');
                $result['msg'] = '当前优惠活动已生效,不能关闭';
                return json($result);
            }else{
                $res = Db::name('discount')
                    ->where('id', $post['id'])
                    ->update(['status' => 2]);
                if ($res !== FALSE) {
                    $result = Config::get('code.success');
                } else {
                    $result = Config::get('code.error');
                }
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-20
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 查询商品审核失败原因
     * @return array|Json
     */
    public function loseProduct(){
        $data = Request::instance()->post();
        $res = Db::name('product_auth')->where('product_id',$data['product_id'])->value('message');
        if ($res){
            $result = Config::get('code.success');
            $result['message'] = $res;
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * 修改商品价格和库存
     * @return \think\response\Json
     */
    public function updateProduct(){
        $data = Request::instance()->post();
        if(!array_key_exists('id',$data) || empty($data['id'])){
            $result = Config::get('code.mistake');
            return json($result);
        }
        Db::startTrans();
        try{
            if (array_key_exists('category_id',$data) && !empty($data['category_id'])){
                $new_category = [['id'=>$data['category_id']],['id'=>$data['type_id']],['id'=>$data['small_type_id']]];
                $info = Db::name('product')->where(['id'=>$data['id']])->find();
                $old_category = [['id'=>$info['category_id']],['id'=>$info['type_id']],['id'=>$info['small_type_id']]];
                foreach ($new_category as $key => $value) {
                    $add = Db::name('base_data')->where(['id'=>$value['id']])->setinc('goods_num');
                }
                foreach ($old_category as $key => $value) {
                    $desc = Db::name('base_data')->where(['id'=>$value['id']])->setdec('goods_num');
                }
                // var_dump($new_category,$old_category);exit;
            }
            $res1 = Db::name('product')->where(['id'=>$data['id']])->strict(false)->update($data);
            // 只修改默认规格的价格
            $res2 = Db::name('product_specification')->where(['product_id'=>$data['id'],'is_default'=>1])->setField('price',$data['price']);
//            $res3 = Db::name('product')->where(['id'=>$data['id']])->setField('name',$data['name']);
            if ($res1 !==false && $res2 !==false){
                Db::commit();
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
                Db::rollback();
            }
        }catch (Exception $e) {
            $result = Config::get('code.error');
            $result['msg'] = $e->getMessage();
            Db::rollback();
        }
        return json($result);
    }


    // private function getCategory(goods_id){
    //     $ids = Db::name('product')->where(['id'=>goods_id,'flag'=>1])
    //             ->file('id,category_id,type_id,small_type_id,brand_id')->find();
    //     $name = [];
    //     var_dump($ids);exit;
    //     // foreach ($ids as $key => $value) {
    //     //     $res = Db::name('base_data')->where(['id'=>$value['']])
    //     // }
    // }


    /**
     * 修改规格，信息获取
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsInfo(){
        $post = Request::instance()->post();
        if (array_key_exists('id', $post) && !empty($post['id'])) {
            $id = $post['id'];
            $info = Db::name('product')
                ->alias('P')
                ->field('P.id,P.name,stock,S.price,P.unit,P.description,P.origin,P.is_include_tax,P.category_id,P.type_id,P.small_type_id,P.brand_id')
                ->field('CASE WHEN B1.name IS NULL THEN B1.name_english ELSE B1.name END as category_name,B1.name_english as categoryEn')
                ->field('CASE WHEN B2.name IS NULL THEN B2.name_english ELSE B2.name END as type_name,B2.name_english as typeEn')
                ->field('CASE WHEN B3.name IS NULL THEN B3.name_english ELSE B3.name END as small_type_name,B3.name_english as small_type_En')
                ->field('CASE WHEN B4.name IS NULL THEN B4.name_english ELSE B4.name END as brand_name,B4.name_english as brandEn')
                ->join('product_specification S','P.id = S.product_id','left')
                ->join('base_data B1','B1.id = P.category_id','left')
                ->join('base_data B2','B2.id = P.type_id','left')
                ->join('base_data B3','B3.id = P.small_type_id','left')
                ->join('base_data B4','B4.id = P.brand_id','left')
                ->where(['P.id'=>$id,'S.is_default'=>1])
                ->find();
            $spec = Db::name('product_specification')
                ->field('')
                ->where(['product_id'=>$info['id'],'flag'=>1])
                ->select();
            foreach ($spec as $key => $value){
                $spec[$key]['price'] = sprintf("%.2f",$value['price']) .Session::get('flag');
            }
            $result = Config::get('code.success');
            $result['data'] = $info;
            $result['data']['spec'] = $spec;
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * 新增商品规格
     * @return \think\response\Json
     */
    public function addSpec(){
        $post = Request::instance()->post();
        if (empty($post['unit']) || empty($post['price']) || empty($post['num'])){
            $result = Config::get('code.mistake');
        }else{
            $data['product_id']         = $post['id'];
            $data['packing_proportion'] = $post['num'];
            $data['unit']               = $post['unit'];
            $data['specification']      = $post['num'].$post['unit'];
            $data['price']              = $post['price'];
            $data['is_default']         = 0;
            $data['flag']               = 1;
            $res = Db::name('product_specification')->insert($data);
            if($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }
        return json($result);
    }

    public function delSpec(){
        $post = Request::instance()->post();
        if (empty($post['id'])){
            $result = Config::get('code.mistake');
        }else{
            // 判断删除的是否是默认规格
            $res = Db::name('product_specification')->delete($post['id']);
            if($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }
        return json($result);
    }
}
